//
//  LYAvatarCertificationController.m
//  Btpin
//
//  Created by liuyan on 2019/4/10.
//  Copyright © 2019年 Vic. All rights reserved.
//

#import "LYAvatarCertificationController.h"

@interface LYAvatarCertificationController ()<PSSingleRowViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    PSSingleRowView *headerPickerView;
    UIImageView *headerImgView;
    
    NSString *url;
}
/**
 图片选择控制器
 */
@property (nonatomic, strong) UIImagePickerController *picker;

/**
 头像
 */
@property (nonatomic,strong)UIImage *upCardImages;

@end

@implementation LYAvatarCertificationController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (headerPickerView) {
        headerPickerView.hidden = YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"头像认证";
    
    [self initUI];
}
- (void)initUI {
    NSMutableArray *headerArray = [NSMutableArray arrayWithCapacity:0];
    PublicCategoryElementModel *model1 = [[PublicCategoryElementModel alloc] init];
    [model1 setValuesForKeysWithDictionary:@{@"id":@"0", @"name":@"拍摄"}];
    [headerArray addObject:model1];
    PublicCategoryElementModel *model2 = [[PublicCategoryElementModel alloc] init];
    [model2 setValuesForKeysWithDictionary:@{@"id":@"1", @"name":@"相册"}];
    [headerArray addObject:model2];
    headerPickerView = [[PSSingleRowView alloc] initWithData:headerArray target:self];
    headerPickerView.hidden = YES;
    
    url = @"";
    
    headerImgView = [UIToolsControl initImageViewWithFrame:CGRectMake((WIDTH-80*Scale)*0.5, 50*Scale, 80*Scale, 80*Scale) imageName:@"header_bg"];
    headerImgView.contentMode = UIViewContentModeScaleAspectFill;
    headerImgView.userInteractionEnabled = YES;
    headerImgView.layer.cornerRadius = 40*Scale;
    headerImgView.layer.masksToBounds = YES;
    [headerImgView sd_setImageWithURL:[NSURL URLWithString:self.avatar]];
    [self.view addSubview:headerImgView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView:)];
    [headerImgView addGestureRecognizer:tap];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( 15, headerImgView.bottom + 10, WIDTH - 30, 20)];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = RGB(85, 85, 85);
    label.text = @"点击上传真实头像";
    label.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:label];
    
    UIButton *certificatBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, label.bottom+60*Scale, WIDTH-80*Scale, 46*Scale) imageName:nil target:self action:@selector(certificatBtnClick:) title:@"认证" titleColor:COLOR_OF_WHITE];
    certificatBtn.layer.cornerRadius = certificatBtn.height/2;
    certificatBtn.layer.masksToBounds = YES;
    certificatBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    certificatBtn.titleLabel.font = Font(Font_17);
    [self.view addSubview:certificatBtn];
    
//    if (self.avatar_audit && [self.avatar_audit isEqualToString:@"1"]) {
//        [certificatBtn setTitle:@"通过认证" forState:UIControlStateNormal];
////        certificatBtn.userInteractionEnabled = NO;
//        certificatBtn.backgroundColor = THEMECOLOR_OF_TEXT_cccccc;
//        [certificatBtn setTitleColor:THEMECOLOR_OF_RED forState:UIControlStateNormal];
//        [certificatBtn setTitle:@"已认证" forState:UIControlStateNormal];
//    }
}

#pragma mark -- Action
//认证
- (void)certificatBtnClick:(UIButton *)button {
    if (url && url.length) {
        SVPHUDShow;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
        dic = [UIToolsControl getPublicParameter];
        [dic setObject:url forKey:@"avatar"];
        
        [BaseNetManager requestWithMethod:POST path:User_SaveAvatar_URL params:dic successBlock:^(NSDictionary *responseObject) {
            if ([responseObject[@"code"] integerValue] == 2000) {
                SVPHUDSuccess(responseObject[@"msg"]);
                
                [self performSelector:@selector(delayClick) withObject:nil afterDelay:0.5];
            } else {
                SVPHUDError(responseObject[@"msg"]);
            }
        } failurBlock:^(NSError *error) {
            SVPHUDError(NetErrorAlertText);
        }];
    } else {
        SVPHUDError(@"请上传头像");
    }
}
- (void)delayClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)tapView:(UITapGestureRecognizer *)tap{
    headerPickerView.hidden = NO;
}
- (void)psSingleRowViewCancel:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
}
- (void)psSingleRowViewOk:(PublicCategoryElementModel *)model PSSingleRowView:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
    if (psSingleRowView == headerPickerView) {
        if ([model.id integerValue] == 1) { // 相册
            [self openPhotoLibrary];
        } else { // 拍摄
            [self openCamera];
        }
    }
}
- (void)openCamera {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相机权限未开启" message:@"相机权限未开启，请进入系统【设置】>【隐私】>【相机】中打开开关,开启相机功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
}
- (void)openPhotoLibrary {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相册权限未开启" message:@"相册权限未开启，请进入系统【设置】>【隐私】>【相册】中打开开关,开启相册功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.navigationBar.translucent = NO;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:imagePicker animated:YES completion:^{
            NSLog(@"打开相册");
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSLog(@"finish..");
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    SVPHUDShow;
    [DataToolsControl uploadImgType:UploadImgTypeOfHeader image:image successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            self->url = data[@"url"];
            self->headerImgView.image = image;
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(@"上传失败，请重新操作");
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}




@end
